import React, { useEffect, useState } from 'react'
import { Layout, Upload, message } from 'antd'
import {
  LoadingOutlined,
  PlusOutlined,
  DownOutlined,
  UpOutlined,
  UserOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import './HeaderComponent.scss'

const { Header } = Layout

const HeaderComponent = () => {
  const [currentTime, setCurrentTime] = useState(
    moment().format('MMMM D, YYYY h:mm A')
  )
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState() //用户头像

  // 定时更新当前时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(moment().format('MMMM D, YYYY h:mm A'))
    }, 1000)
    return () => clearInterval(timer) // 清除定时器
  }, [])

  const getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
    }
    return isJpgOrPng && isLt2M
  }

  // 点击上传头像
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    } else if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false)
        setImageUrl(url)
      })
    } else if (info.file.status === 'error') {
      message.error('上传失败，请稍后重试')
      setLoading(false)
    }
  }

  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
      }}
      type="button">
      <div>
        <UserOutlined />
      </div>
    </button>
  )

  return (
    <Header className="header">
      {/* 左侧的文字在一行显示 */}
      <div className="left-text">
        <h1>WizDepot</h1>
        <h3>My Timesheet</h3>
      </div>

      {/* 右侧的时间和头像框 */}
      <div className="right-content">
        <h4 className="time">{currentTime}</h4>
        <div className="userAvatar">
          <Upload
            name="avatar"
            listType="picture-circle"
            className="avatar-uploader"
            showUploadList={false}
            // action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
            beforeUpload={beforeUpload}
            onChange={handleChange}>
            {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
          </Upload>
        </div>
        {imageUrl ? (
          <UpOutlined className="user-icon" />
        ) : (
          <DownOutlined className="user-icon" />
        )}
      </div>
    </Header>
  )
}

export default HeaderComponent
